﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using OnlineEducation.Controllers;
using OnlineEducation.Data;
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using OnlineEducation.Extensions;
using System.Collections.Generic;
using OnlineEducation.Data.Entities;
using OnlineEducation.Models.JQueryTable;
using OnlineEducation.Helpers.JQueryTable;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using OnlineEducation.Helpers;
using Microsoft.CodeAnalysis.Operations;
using NPOI.SS.UserModel.Charts;
using System.Security.Policy;
using OnlineEducation.Models;
using OnlineEducation.Models.ServerAPIModels;
using OnlineEducation.Constants;
using OnlineEducation.Models.CourseViewModels;
using System.Net.NetworkInformation;
using Microsoft.Extensions.Configuration;

namespace OnlineEducation.Areas.Controllers
{
    /// <summary>
    /// Course management, you can query, add, edit, delete products
    /// </summary>
    [Area("Booking")]
    [Route("[controller]/[action]")]
    [Authorize(Roles = "Student")]
    public class BookingController : BaseController
    {
        private readonly ILogger _logger;
        private readonly ApplicationDbContext _context;
        private readonly IWebHostEnvironment _env;
        private readonly IConfiguration _configuration;

        public BookingController(ApplicationDbContext context, ILogger<BookingController> logger, IWebHostEnvironment env, IConfiguration configuration)
        {
            _context = context;
            _logger = logger;
            _env = env;
            _configuration = configuration;


        }
        /// <summary>
        /// Get all teaching plans
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost("{status}")]
        public IActionResult Courses(int status = 0)
        {

            var courseinfos = _context.Courses.Include(r => r.Lessons).Include(n => n.Teacher).Where(n => n.Status == status).Select(r =>
              new CourseSummaryModel
              {
                  CourseId = r.Id,
                  CourserSubTitle = r.SubTitle,
                  CourseTitle = r.Title,
                  Description = r.Description,
                  TeacherId = r.TeacherId.HasValue ? r.TeacherId.Value : 0,
                  TeacherImage = string.Empty,
                  TeacherName = r.Teacher.FullName,
                  LessionCount = r.Lessons.Count,
                  TeacherTitle = r.Teacher.Title,
                  StudentCount = 0

              }).ToList();
            var studentinfo = _context.TeachingPlans.Include(r => r.Course).Where(r => r.Course.Status == status).ToList();
            var evulationinfo = _context.CourseEvaluations.Include(r => r.TeachingPlan).ThenInclude(r => r.Course).Where(r => r.TeachingPlan.Course.Status == status).ToList();
            foreach (var item in courseinfos)
            {
                var student = studentinfo.FirstOrDefault(r => r.CourseId == item.CourseId);
                var evulation = evulationinfo.Where(r => r.TeachingPlan.CourseId == item.CourseId);
                if (student != null)
                {
                    item.StudentCount = student.StudentPlanCount;
                }
                item.EvulationCount = evulation.Count();
            }

            return PartialView("_courseList", courseinfos);
        }

        /// <summary>
        /// Get teaching plans detail
        /// </summary>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> Detail(int id)
        {

            var userid = User.GetUserID();

            var myTeachingPlans = await _context.Bookings.Include(n => n.TeachingPlan)
                .Where(n => n.StudentId == userid && n.TeachingPlan.Category == 1)
               .Select(n => n.TeachingPlan).ToListAsync();

            ViewBag.MyTeachingPlans = myTeachingPlans;

            var courseinfo = await _context.Courses.Where(r => r.Id == id).Include(r => r.Teacher).Include(r => r.Lessons).FirstOrDefaultAsync();
            var teachPlans = await _context.TeachingPlans.Where(r => r.CourseId == id).Include(r => r.TeachingPlanItems).Include(r => r.Evaluations).Include(r => r.Course).ThenInclude(l => l.Lessons).ToListAsync();
            var planIds = teachPlans.Select(r => r.Id).ToList();
            var bookings = await _context.Bookings.Where(r => planIds.Contains(r.TeachingPlanId)).ToListAsync();
            var courseDetail = new CourseDetailModel
            {
                Course = courseinfo,
                TeachingPlans = teachPlans,
                EvaluationCount = teachPlans.SelectMany(r => r.Evaluations).Count(),
                Bookings = bookings
            };
            return View(courseDetail);
        }


        /// <summary>
        /// Get teaching plan detail
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add(int id)
        {
            try
            {
                var tp = await _context.TeachingPlans.Include(k => k.Course).Where(n => n.Id == id).FirstOrDefaultAsync();

                var bookingCount = _context.Bookings.Count() + 1;

                var booking = new Booking
                {
                    TeachingPlanId = id,
                    StudentId = User.GetUserID(),
                    Status = 1,
                    TotalAmount = tp.Course.Price,
                    Discount = 0,
                    BookingNo = bookingCount.ToString().PadLeft(5, '0'),
                };



                _context.Add(booking);

                await _context.SaveChangesAsync();

                return Json(new { success = true, message = "预定成功." });

            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }



        /// <summary>
        /// Get my plan detail
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetMyBookings(Period peroid)
        {
            try
            {
                int studentId = User.GetUserID();

                var myBookings = await _context.Bookings.Include(k => k.TeachingPlan).ThenInclude(n => n.TeachingPlanItems).ThenInclude(n => n.Lesson)
                    .Where(n => n.StudentId == studentId).ToListAsync();

                List<MyEvent> list = new List<MyEvent>();

                foreach (var item in myBookings)
                {
                    var tp = item.TeachingPlan;


                    if (tp.Category == 2)
                    {
                        MyEvent e = new MyEvent
                        {
                            Id = tp.TeachingPlanItems[0].Id,
                            Title = tp.Name,
                            Description = "临时计划",
                            PreviewMaterialURLs = tp.MaterialURLs,
                            Start = tp.TeachingPlanItems[0].BeginTime,
                            AdhocPlan = true
                        };

                        list.Add(e);
                    }
                    else
                    {

                        foreach (var l in tp.TeachingPlanItems)
                        {
                            MyEvent e = new MyEvent
                            {
                                Id = l.Id,
                                Title = l.Lesson.Title,
                                LessonId = l.LessonId,
                                Chapter = l.Lesson.Chapter,
                                Description = l.Lesson.Description,
                                Duration = l.Lesson.Duration.ToString(),
                                PreviewMaterialURLs = l.Lesson.PreviewMaterialURLs,
                                Section = l.Lesson.Section,
                                Start = l.BeginTime,
                                End = l.BeginTime.AddMinutes(l.Lesson.Duration),
                                AdhocPlan = false

                            };

                            list.Add(e);
                        };
                    }
                }

                return Json(new { success = true, data = list });

            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// Get lesson detail
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetTeachingPlanItem(int id, bool adhoc)
        {

            if (!adhoc)
            {

                var teachingPlan = await _context.TeachingPlans.Include(n => n.TeachingPlanItems)
                    .ThenInclude(n => n.Lesson).Include(n => n.Teacher).Include(n => n.Course)
                    .Where(n => n.TeachingPlanItems.Any(n => n.Id == id)).FirstOrDefaultAsync();

                if (teachingPlan == null)
                {
                    return PartialView("_Lesson", new LessonModel());
                }

                var teachingPlanItem = teachingPlan.TeachingPlanItems.Where(n => n.Id == id).FirstOrDefault();

                var lessonModel = new LessonModel
                {
                    CourseTitle = teachingPlan.Course.Title,
                    BeginTime = teachingPlanItem.BeginTime,
                    ChapterSection = "第" + teachingPlanItem.Lesson.Chapter + "章 第" + teachingPlanItem.Lesson.Chapter + "节",
                    CurrentLesson = teachingPlanItem.Lesson.Sequence,
                    TotalLessonCount = teachingPlan.TeachingPlanItems.Count,
                    LessonTitle = teachingPlanItem.Lesson.Title,
                    LessonStatus = teachingPlanItem.Status,
                    PreviewMaterialURL = teachingPlanItem.Lesson.PreviewMaterialURLs,
                    TeacherName = teachingPlan.Teacher.FullName,
                    MeetingNo = teachingPlanItem.MeetingNo
                };
                return PartialView("_Lesson", lessonModel);
            }
            else
            {


                var teachingPlanItem = _context.TeachingPlanItems.Where(n => n.Id == id).FirstOrDefault();

                if (teachingPlanItem == null)
                {
                    return PartialView("_Lesson", new LessonModel());
                }
                var teachingPlan = await _context.TeachingPlans.Include(n => n.TeachingPlanItems)
                   .Include(n => n.Teacher).Where(n => n.Id == teachingPlanItem.TeachingPlanId).FirstOrDefaultAsync();


                var lessonModel = new LessonModel
                {
                    CourseTitle = teachingPlan.Name,
                    BeginTime = teachingPlanItem.BeginTime,
                    ChapterSection = "临时计划",
                    CurrentLesson = 1,
                    TotalLessonCount = 1,
                    LessonTitle = teachingPlan.Name,
                    LessonStatus = teachingPlanItem.Status,
                    PreviewMaterialURL = teachingPlan.MaterialURLs,
                    TeacherName = teachingPlan.Teacher.FullName,
                    MeetingNo = teachingPlanItem.MeetingNo
                };
                return PartialView("_adhocLesson", lessonModel);
            }


        }

        [HttpPost]
        public async Task<IActionResult> GetMaterialURLs(string meetingno)
        {

            var planitem = await _context.TeachingPlanItems.Include(n => n.Lesson).Where(n => n.MeetingNo == meetingno).FirstOrDefaultAsync();


            return Json(new { success = !string.IsNullOrEmpty(planitem.Lesson.MaterialURLs), url = planitem.Lesson.MaterialURLs });

        }
        [HttpPost]
        public async Task<IActionResult> CheckMeetingStatus(string meetingno)
        {

            var planitem = await _context.TeachingPlanItems.Where(n => n.MeetingNo == meetingno).FirstOrDefaultAsync();


            return Json(new { success = true, status = planitem.Status });

        }


        [HttpPost]
        public IActionResult BuildJoinMeetingParams(string meetingno)
        {

            var server_address = _configuration.GetSection("BBB_Server_Address").Value;

            var meeting = new SearchMeetingInfo();

            meeting.meetingID = meetingno;

            var param = Utility.CreateParams<SearchMeetingInfo>(meeting, ServerAPI.GetMeetingInfo);

            var httprequest = HttpHelper.HttpsGet($"{server_address}/bigbluebutton/api/getMeetingInfo?" + param);

            var response = Utility.XMLToModel<SearchMeetingInfoResponseEntity>(httprequest);

            if (response.returncode == "SUCCESS")
            {

                var joinmeeting = new JoinMeeting
                {
                    fullName = User.Identity.Name,
                    meetingID = meetingno,
                    password = "111111",
                    userID = User.GetUserID().ToString(),
                    redirect = "true", // true,直接返回了html页面， 为false的时候，返回xml结果，包含会议地址
                    joinViaHtml5 = "true",
                    clientURL = $"{server_address}/",
                    //avatarURL=
                };
                var param1 = Utility.CreateParams<JoinMeeting>(joinmeeting, ServerAPI.Join);

                var joinurl = $"{server_address}/bigbluebutton/api/join?" + param1;

                return Json(new { success = true, url = joinurl });

            }
            else
            {
                _logger.LogError($"Meeting room with No {meetingno} cannot enter in.");

                return Json(new { success = false, message = "教室未创建或已关闭，不能进入，请联系管理员。" });
            }

        }


    }



}
